<template>
  <div :style="{ padding: '15px' }">
    <el-collapse
      accordion
      v-for="(v, k) in getuserquestion"
      :key="`${k}_3`"
      class="border-0 question-collapse"
    >
      <el-row class="border-bottom">
        <div class="txt col pl-0 pr-0">
          <div class="float-start">
            <strong
              :class="
                ALLTYPE[v.resultdata]
                  ? ALLTYPE[v.resultdata][1]
                  : ALLTYPE['WT'][1]
              "
            >
              {{
                ALLTYPE[v.resultdata]
                  ? ALLTYPE[v.resultdata][1]
                  : ALLTYPE["WT"][1]
              }}
            </strong>
          </div>
          <div class="float-right tjsj text-right">
            <span>提交时间： {{ TimeYH(v.createdAt) }}</span>
            <span
              >编程语言：{{
                v.language
                  ?.toLowerCase()
                  .replace(/( |^)[a-z]/g, (L) => L.toUpperCase()) !== "Cpp"
                  ? v.language
                      ?.toLowerCase()
                      .replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
                  : "C++"
              }}</span
            >
          </div>
          <span class="clearfix"></span>
        </div>
      </el-row>
      <div v-if="Array.isArray(v.info)">
        <el-row class="mt-2 mb-2">
          <h5 class="col">测试点信息</h5>
          <div v-if="k === 0" :style="{ width: '150px', textAlign: 'right' }">
            <el-button
              size="default"
              type="primary"
              v-if="length < 30"
              @click="centerDialogVisible = true"
              >贡献测试点
            </el-button>
          </div>
        </el-row>
        <div
          class="row"
          v-for="(info1, infok) in subtask(v.info)"
          :key="'a_' + infok"
        >
          <div class="col-12">Subtask {{ infok + 1 }}</div>
          <div class="col-12">
            <div
              class="classtz border text-center"
              v-for="(e, k) in info1"
              :key="`b_${k}`"
              :class="e.tn ? e.tn[1] : ALLTYPE['RE'][1]"
              @mouseleave="mouseleave"
              @mouseenter="mouseenter"
            >
              <div class="div-1-1">
                <div class="text-left">#{{ k + 1 }}</div>
                <strong
                  class="text-uppercase"
                  v-text="e.tn ? e.tn[0] : 'RE'"
                ></strong>
                <br />
                <span>{{ time([e]) }}/{{ memory(e) }}</span>
              </div>
              <el-collapse-transition>
                <div @click="downloadtestcase(e.ID, k)" class="transition">
                  <div>下载测试点</div>
                </div>
              </el-collapse-transition>
            </div>
          </div>
        </div>
      </div>

      <el-row v-else>
        <div class="col p-0 mb-4 mt-4">
          <h5>错误提示</h5>
          <pre class="m-0" v-text="v.info?.msg"></pre>
        </div>
      </el-row>
      <el-row>
        <div class="col p-0">
          <h5>源代码</h5>
          <pre :class="'language-' + v.language">
          <code >{{ v.context }}</code></pre>
        </div>
      </el-row>
    </el-collapse>
    <div class="text-right">
      <br />
      <el-pagination
        :page-size="10"
        :total="count"
        @current-change="(r) => (offset = 10 * (r - 1))"
        layout="prev, pager, next, jumper"
        :current-page="Math.floor(offset / 10) + 1"
      ></el-pagination>
      <br />
    </div>
    <el-dialog
      v-model="centerDialogVisible"
      class="my_el-dialog__body"
      title="添加测试点"
      width="950px"
    >
      <div class="testcase">
        <div class="row">
          <div class="col">
            感谢您为这道题贡献测试点！~\(≥▽≤)/~
            <br />
            为了保证题解质量，您提交的测试点我们会在第一时间进行审核，通过后会作为后续评测的标准测试点展示。
          </div>

          <div class="col-2 text-right">
            <el-popover placement="left-start" :width="400" trigger="click">
              <template #reference>
                <el-button class="disbutton">
                  审核规则 &nbsp;
                  <el-icon :size="16">
                    <QuestionFilled />
                  </el-icon>
                </el-button>
              </template>
              <div>
                <div>审核将按照以下规则：</div>
                <div>1）测试点正确：测试点需要完全符合题目要求、确保正确；</div>
                <div>
                  2）测试点无重复：当前已有测试点中，没有完全重复或基本重复的测试点。
                </div>
                <div>如对测试点有疑问，可以添加网站右上角助教老师沟通。</div>
                <br />
                <div>每贡献一个测试点并审核通过，+1贡献积分，+1金币。</div>
                <div>贡献积分会持续累加，不会消耗。</div>
              </div>
            </el-popover>
          </div>
        </div>

        <el-row> </el-row>
        <div class="h33"></div>
        <el-row class="ex">
          <el-col :span="24" class="text-right">
            <el-popover placement="bottom" :width="400" trigger="click">
              <template #reference>
                <el-button size="default" text :style="{ marginRight: '12px' }">
                  上传说明
                  <el-icon :size="16">
                    <QuestionFilled />
                  </el-icon>
                </el-button>
              </template>
              <div>
                <div>文件形式上传测试点要求：</div>
                <div>1）测试点文件打包成zip文件；</div>
                <div>
                  2）每一个测试点文件需要相同名称的两个文件,输入文件为.in，输出文件为.out或者.ans；
                </div>
                <div>
                  3）目前支持输入输出单个文件最大为1GB，后续会对部分题目开放更大空间。
                </div>
              </div>
            </el-popover>
            <el-upload
              :disabled="length > 30"
              action="/"
              :show-file-list="false"
              accept=".zip"
              :http-request="request"
              class="d-inline-block"
            >
              <el-button size="default" type="primary" :disabled="length > 30"
                >上传测试点</el-button
              >
            </el-upload>
          </el-col>
        </el-row>
        <el-form
          ref="form"
          class="container-xl form-xl"
          :model="formrule"
          label-width="120px"
        >
          <div class="row">
            <div class="col">输入</div>
            <div class="col">输出</div>
            <div :style="{ width: '48px' }">
              <el-icon
                class="el-icon-1"
                @click="usertest.push({ input: '', output: '' })"
              >
                <Plus />
              </el-icon>
            </div>
          </div>
          <div
            class="row"
            :style="{ marginTop: '12px' }"
            v-for="(n, m) in usertest"
            :key="'1_' + m"
          >
            <div class="col">
              <el-input
                :type="n.type ? 'text' : 'textarea'"
                v-model="n.input"
                :rows="5"
                :disabled="n.type == 'url'"
                placeholder="测试点输入"
              ></el-input>
            </div>
            <div class="col">
              <el-input
                :type="n.type ? 'text' : 'textarea'"
                v-model="n.output"
                :rows="5"
                :disabled="n.type == 'url'"
                placeholder="测试点输出"
              ></el-input>
            </div>
            <div :style="{ width: '48px' }">
              <el-icon class="el-icon-2" @click="usertest.splice(m, 1)">
                <Minus />
              </el-icon>
            </div>
          </div>
          <div class="m-mt-6 m-mb-3">备注</div>
          <div>
            <el-input type="textarea" v-model="usercont" :rows="2"></el-input>
          </div>
        </el-form>
        <el-row>
          <el-col :span="12"></el-col>
          <el-col :span="12" class="text-right">
            <el-button
              size="default"
              type="primary"
              @click="submit"
              v-show="length < 30"
              :disabled="length > 30"
              >提交审核
            </el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Minus, Plus, QuestionFilled } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import { computed, h, nextTick, onMounted, reactive, ref, watch } from "vue";
import { useStore } from "vuex";
import {
  asynccreatequestiontestcasesuser,
  asyncselectuserquestion,
} from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { ALLTYPE } from "@/util/jianchatime";
import subtask from "../../../util/subtask";
import { TimeYH } from "../../../util/time";
import { memory, time } from "../../../util/code";
import { ElPagination } from "element-plus";
import type { Action } from "element-plus/lib/components";
import highlight from "highlight.js";
import { useRoute } from "vue-router";
import { downloadtext } from "../../../util/dowmload";
import { updatezip } from "../../../util/updateoss";
type P = {
  isSub: boolean;
  user: Studycodemodel.Iuser;
  ID?: number;
  question: Studycodemodel.Iquestion;
};
interface Iusertest extends Studycodemodel.Iquestiontestcasesuser {}
const prop = defineProps<P>();

const usertest = ref<Iusertest[]>([{ input: "", output: "" }]);

const length = computed(() => {
  return prop.question.testcases?.length || 0;
});

const route = useRoute();

const range = computed(() => {
  return route.query.range;
});

const formrule = reactive({});
const usercont = ref("");
const centerDialogVisible = ref(false);
const activeNames = ref("");
const userquestion = ref<Studycodemodel.Iuserquestion[]>([]);
const offset = ref(0);
const count = ref(0);
const store = useStore(Storekey);
const user = computed(() => {
  return store.state.user;
});

watch(
  () => prop.isSub,
  (v) => {
    if (v) {
      start();
    }
  }
);

watch(
  () => offset.value,
  (v) => {
    start();
  }
);

onMounted(() => {
  start();
});

watch(
  () => prop.ID,
  () => {
    start();
  }
);

const getuserquestion = computed(() => {
  return userquestion.value;
});

async function start() {
  if (user.value && prop.ID) {
    const data = await asyncselectuserquestion({
      _offset: offset.value,
      userid: user.value.ID,
      _limit: 10,
      questionid: prop.ID,
      _order: "ID",
      _sortable: "DESC",
    });
    userquestion.value = data.rows;
    count.value = data.count;
    nextTick(() => {
      highlight.highlightAll();
    });
  }
}

defineExpose({
  start,
  count,
});

function downloadtestcase(ID?: number, index?: number) {
  fetch(`/api/download/downloadtestcase?ID=${ID}`)
    .then((e) => e.json())
    .then(
      (e: { error: number; msg: string; data: Studycodemodel.Itestcases }) => {
        if (e.error) {
          ElMessage.error(e.msg);
          return;
        }
        const data: { name: string; text: string }[] = [];
        if (e.data.input) {
          data.push({
            name: `${index}.in`,
            text: e.data.input,
          });
        }
        if (e.data.output) {
          data.push({
            name: `${index}.out`,
            text: e.data.output,
          });
        }
        if (e.data) {
          downloadtext(e.data.type, prop.ID + "_" + index, data);
        } else {
          ElMessage.error("文件找不到");
        }
      }
    );
}
function mouseleave(e: MouseEvent) {
  if (range.value === "codeforces") return;
  if (e.target) {
    const n: any = e.target;
    n.querySelector(".div-1-1").style.display = "block";
    const div: HTMLDivElement = n.querySelector(".transition");

    const bgcolor = Object.values(ALLTYPE)
      .map((e) => e[1])
      .find((t) => {
        return n.className.includes(t);
      });
    div.style.display = "none";
    div.className = `transition bg-${n.className}`;
    div.style.height = "0";
  }
}

function mouseenter(e: MouseEvent) {
  if (range.value === "codeforces") return;

  if (e.target) {
    const n: any = e.target;
    n.querySelector(".div-1-1").style.display = "none";
    const div: HTMLDivElement = n.querySelector(".transition");
    const bgcolor = Object.values(ALLTYPE)
      .map((e) => e[1])
      .find((t) => {
        return n.className.includes(t);
      });
    div.style.display = "flex";
    div.className = `transition bg-${bgcolor}`;
    div.style.height = "100%";
  }
}

function submit() {
  const data: Studycodemodel.Iquestiontestcasesuser[] = [];
  usertest.value.forEach((e) => {
    const { ...t } = e;
    if (e.input && e.output) {
      t.context = usercont.value;
      t.questionid = prop.ID;
      t.userid = user.value?.ID;
      data.push(t);
    }
  });
  if (data.length) {
    asynccreatequestiontestcasesuser({ questiontestcasesuser: data })
      .then((n) => {
        usertest.value = [{ input: "", output: "" }];
        ElMessage.success("提交成功");
        ElMessageBox({
          title: "提交成功",
          message: h("p", null, [
            h("img", {
              src: "https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/JOY/image/Banner_1",
              width: "488",
            }),
            h(
              "span",
              null,
              "我们会在24小时内审核完成，通过后会进行公开展示并增加您的贡献积分。"
            ),
            h("br", null, ""),
            h("br", {}, ""),
            h("span", {}, "贡献将按照以下规则："),
            h("br", {}, ""),
            h(
              "span",
              {},
              "1）测试点正确：测试点需要完全符合题目要求、确保正确；"
            ),
            h("br", {}, ""),
            h(
              "span",
              {},
              "2）测试点无重复：当前已有测试点中，没有完全重复或基本重复的测试点。"
            ),
            h("br", {}, ""),
            h("br", {}, ""),
            h("span", {}, "如对测试点有疑问，可以添加网站右上角助教老师沟通。"),
          ]),
          customStyle: {
            width: "520px",
          },
          confirmButtonText: "好的",
          callback: (action: Action) => {
            centerDialogVisible.value = false;
          },
          buttonSize: "default",
        });
      })
      .catch((n) => {
        ElMessage.error(n);
      });
  } else {
    ElMessage.success("请填写测试点");
  }
}

async function request(file: { file: File }, c: Function) {
  const { size } = file.file;
  if (size > 1024 * 1024 * 1024) {
    ElMessage.error("上传文件过大，最大只能上传1GB");
    return;
  }
  ElNotification({
    title: "解压",
    message: "开始解压",
    type: "info",
  });

  const data = await updatezip(file.file);
  data.forEach((e) => {
    const { input, output } = e;
    usertest.value.push({
      input,
      output,
      userid: user.value?.ID,
      questionid: prop.ID,
      type: "url",
    });
  });
  ElNotification({
    title: "解压",
    message: "解压成功",
    type: "success",
  });
  c("a.zip");
}
</script>

<style scoped>
.table pre {
  margin-bottom: 0px;
}

h5 {
  font-size: 16px;
}

.txt {
  padding-bottom: 12px;
}

.txt strong {
  line-height: 36px;
  padding-right: 10px;
  font-size: 32px;
  display: inline-block;
}

.div-hr {
  height: 41px;
  padding-top: 20px;
  padding-bottom: 20px;
}

.div-hr div {
  height: 1px;
  background-color: cornsilk;
}

.question-collapse {
  margin-bottom: 40px;
}

.question-collapse img {
  line-height: 40px;
}

.tjsj {
  line-height: 32px;
  text-align: end;
}

.tjsj span {
  display: inline-block;
  padding-right: 10px;
  color: var(--color-606266);
}

.text-hide {
  padding-left: 10px;
  padding-top: 6px;
}

.classtz {
  width: 166px;
  height: 166px;
  display: inline-block;
  margin-right: 20px;
  margin-bottom: 20px;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0px 3px 6px rgba(141, 141, 141, 0.16);
}

.classtz .div-1-1 {
  border-top-width: 10px;
  border-top-style: solid;
}

.co9A97AD {
  color: #9a97ad;
}

.div-1-1 .text-left {
  font-size: 24px;
  margin-top: 10px;
  padding-left: 10px;
  color: #909399 !important;
}

.div-1-1 .text-uppercase {
  font-size: 38px;
  display: inline-block;
  margin-bottom: 10px;
}

.transition {
  transition: 1s all ease;
  display: none;
  color: #fff;
  text-align: center;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 18px;
  font-weight: bold;
}

.div-1-1 span {
  font-size: 14px;
  font-weight: 400;
  line-height: 16px;
  color: #c0c4cc;
}

.context1 {
  border: 1px solid #d9d9d9;
}

.list-group-item {
  border-left: none;
  border-top: none;
  border-bottom: none;
  border-right: 1px solid #d9d9d9;
  cursor: pointer;
  background-color: #f5f5f5;
}

.list-group-item:hover {
  background-color: #fff;
}

.list-group-horizontal {
  width: 100%;
  border-left: 1px solid #d9d9d9;
  border-top: 1px solid #d9d9d9;
  border-bottom: none;
  border-right: 1px solid #d9d9d9;
  border-bottom-left-radius: inherit;
  border-bottom-right-radius: inherit;
  overflow-x: auto;
}

.testcase .pre {
  border-color: #d9d9d9;
  border: 1px solid #d9d9d9;
  padding: 12px;

  box-shadow: 0px 0.3px 0.9px rgba(0, 0, 0, 0.1),
    0px 1.6px 3.6px rgba(0, 0, 0, 0.13);
  border-bottom-left-radius: 2px;
  border-bottom-right-radius: 2px;
}

.testcase pre {
  border: none;
  background-color: #f5f5f5;
}

.h33 {
  font-size: 18px;
  color: var(--color-43);
  margin-top: 24px;
  margin-bottom: 12px;
}

.ex {
  margin-bottom: 12px;
}

.ex1 {
  font-size: 12px;
  color: #8c8c8c;
}

.form-xl {
  border: 1px solid #d9d9d9;
  /* Depth 4 */

  box-shadow: 0px 0.3px 0.9px rgba(0, 0, 0, 0.1),
    0px 1.6px 3.6px rgba(0, 0, 0, 0.13);
  border-radius: 2px;
  padding-top: 12px;
  padding-bottom: 12px;
  margin-bottom: 12px;
}

.el-form .row {
  --bs-gutter-x: 24px;
}

.el-icon-1 {
  width: 24px;
  height: 24px;
  background-color: var(--color-cheng);
  line-height: 24px;
  color: #fff;
  border-radius: 2px;
  text-align: center;
  cursor: pointer;
}

.el-icon-2 {
  width: 24px;
  height: 24px;
  background-color: #d9d9d9;
  line-height: 24px;
  color: #fff;
  border-radius: 2px;
  text-align: center;
  cursor: pointer;
}

.disbutton {
  border: none;
  background-color: #f5f5f5;
  --el-button-hover-color: "#000";
  --el-button-hover-background-color: #f5f5f5;
  height: 28px;
  line-height: 28px;
  padding-top: 0;
  padding-bottom: 0;
  padding-left: 12px;
  padding-right: 12px;
}
</style>

<style>
.question-collapse .is-active {
  background-color: var(--color-d2e4ff) !important;
  border-bottom-width: 0;
}

.question-collapse .el-collapse-item__content {
  padding-bottom: 0 !important;
}
</style>
